#include "widget.h"
#include "ui_widget.h"


#include "QTimer"
#include "QElapsedTimer"
#include "QTime"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    m_timer = new QTimer(this);
    m_timer->stop();
    m_timer->setTimerType(Qt::CoarseTimer);
    ui->radioButton_Coarse->setChecked(true);
    connect(m_timer, &QTimer::timeout, this, &Widget::do_timer_timeout);
    m_counter = new QElapsedTimer();
}

Widget::~Widget()
{
    delete m_counter;
    delete ui;
}

/**
 * @brief 开始按钮按下
 */
void Widget::on_pushButton_Start_clicked()
{
    m_timer->setInterval(ui->spinBox_Interval->value());//设定间隔
    if(ui->radioButton_Contiue->isChecked())
    {
        m_timer->setSingleShot(false);
    }
    else
    {
        m_timer->setSingleShot(true);
    }
    if(ui->radioButton_Precise->isChecked())//选择了高精度
    {
        m_timer->setTimerType(Qt::PreciseTimer);
    }
    else if(ui->radioButton_Coarse->isChecked())//选择了粗糙
    {
        m_timer->setTimerType(Qt::CoarseTimer);
    }
    else if(ui->radioButton_VeryCoarse->isChecked())//选择了非常粗糙
    {
        m_timer->setTimerType(Qt::VeryCoarseTimer);
    }
    m_timer->start();
    m_counter->start();
    ui->pushButton_Start->setEnabled(false);//跑起来了，开始按钮禁用
    ui->pushButton_Stop->setEnabled(true);//跑起来了，停止按钮启用
    ui->pushButton_OneShot->setEnabled(false);//跑起来了，创建按钮禁用
}

void Widget::do_timer_timeout()
{
//    QApplication::beep();
    QTime currentTime = QTime::currentTime();
    //显示时间
    ui->lcdNumber_Hour->display(currentTime.hour());
    ui->lcdNumber_Minute->display(currentTime.minute());
    ui->lcdNumber_Second->display(currentTime.second());

    if(m_timer->isSingleShot())
    {
        int elapsed_time = m_counter->elapsed();//流逝的时间
        QString str = QString("流逝的时间：%1毫秒").arg(elapsed_time);
        ui->label_Elapsed->setText(str);

        ui->pushButton_Start->setEnabled(true);
        ui->pushButton_Stop->setEnabled(false);
        ui->pushButton_OneShot->setEnabled(true);

    }
}

/**
 * @brief 停止按钮按下
 */
void Widget::on_pushButton_Stop_clicked()
{
    m_timer->stop();
    int elapsed_time = m_counter->elapsed();//流逝的时间
    int s = elapsed_time / 1000;
    int ms = elapsed_time % 1000;
    QString str = QString("流逝的时间：%1秒，%2毫秒").arg(s).arg(ms);
    ui->label_Elapsed->setText(str);

    ui->pushButton_Start->setEnabled(true);//停止了，开始按钮启用
    ui->pushButton_Stop->setEnabled(false);//停止了，停止按钮禁用
    ui->pushButton_OneShot->setEnabled(true);//停止了，创建按钮启用
}

/**
 * @brief 动态创建单次定时器按下
 */
void Widget::on_pushButton_OneShot_clicked()
{
    int interval = ui->spinBox_Interval->value();
    m_timer->setSingleShot(true);
    QTimer::singleShot(interval, Qt::PreciseTimer, this, &Widget::do_timer_timeout);
    m_counter->start();
    ui->pushButton_Start->setEnabled(false);//跑起来了，开始按钮禁用
    ui->pushButton_Stop->setEnabled(true);//跑起来了，停止按钮启用
    ui->pushButton_OneShot->setEnabled(false);//跑起来了，创建按钮禁用
}

